package com.lam.mall.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.lam.common.base.page.PageVo;
import com.lam.common.base.page.TableHelper;
import com.lam.common.constant.CommonConstant;
import com.lam.common.constant.MallStateConstant;
import com.lam.common.context.TokenUtils;
import com.lam.common.exception.BusinessException;
import com.lam.common.exception.ParameterErrorException;
import com.lam.common.utils.DateUtil;
import com.lam.common.utils.NumberUtil;
import com.lam.common.utils.StringUtils;
import com.lam.mall.app.vo.MyOrderVo;
import com.lam.mall.app.vo.OrderCountDataVo;
import com.lam.mall.app.vo.ShopCartItemDiscountVo;
import com.lam.mall.app.vo.ShopCartItemVo;
import com.lam.mall.app.vo.ShopCartOrderMergerVo;
import com.lam.mall.app.vo.ShopCartOrderVo;
import com.lam.mall.common.event.CancelOrderEvent;
import com.lam.mall.common.event.ReceiptOrderEvent;
import com.lam.mall.common.event.SubmitOrderEvent;
import com.lam.mall.entity.Order;
import com.lam.mall.entity.OrderAddr;
import com.lam.mall.entity.OrderItem;
import com.lam.mall.entity.OrderLog;
import com.lam.mall.entity.OrderSettlement;
import com.lam.mall.entity.ProdSku;
import com.lam.mall.entity.Product;
import com.lam.mall.enums.OrderStatus;
import com.lam.mall.enums.PayStatus;
import com.lam.mall.mapper.BasketMapper;
import com.lam.mall.mapper.OrderLogMapper;
import com.lam.mall.mapper.OrderMapper;
import com.lam.mall.mapper.OrderSettlementMapper;
import com.lam.mall.mapper.ProdSkuMapper;
import com.lam.mall.mapper.ProductMapper;
import com.lam.mall.param.DeliveryOrderParam;
import com.lam.mall.param.OrderParam;
import com.lam.mall.service.OrderAddrService;
import com.lam.mall.service.OrderItemService;
import com.lam.mall.service.OrderService;
import com.lam.mall.service.ProdSkuService;
import com.lam.mall.service.ProductService;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Snowflake;

/**
 * 订单Service业务层处理
 * 
 * @author admin
 * @date 2023-04-25
 */
@Service
public class OrderServiceImpl  implements OrderService {
	
	 private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderLogMapper orderLogMapper;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private OrderAddrService orderAddrService;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProdSkuMapper prodSkuMapper;
    @Autowired
    private ProductService productService;
    @Autowired
    private ProdSkuService prodSkuService;
    @Autowired
    private Snowflake snowflake;
    @Autowired
    private OrderSettlementMapper orderSettlementMapper;
    @Autowired
    private BasketMapper basketMapper;
    
    @Autowired
    private ApplicationEventPublisher eventPublisher;

    @Override
	public List<MyOrderVo> listPageByUserId(String userId, Integer status) {
    	PageVo pageVo = TableHelper.getPageVo();
    	Page<MyOrderVo> page = new Page<>(pageVo.getPageNum(), pageVo.getPageSize());
    	page.setTotal(orderMapper.listByUserIdCount(userId, status));
    	if(page.getTotal() > 0) {
    		page.addAll(orderMapper.listByUserId(pageVo, userId, status));
    	}
        return page;
	}
    
    /**
     * 查询订单
     * @param orderNo 订单号
     * @return 单个对象
     */
    @Override
    @Transactional(readOnly = true)
    public Order selectSimpleByOrderNo(String orderNo) {

        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_number", orderNo);
        return orderMapper.selectOne(queryWrapper);
    }
    
    /**
     * 查询订单
     * @param orderNo 订单号
     * @return 单个对象
     */
    @Override
    @Transactional(readOnly = true)
    public Order selectByOrderNo(String orderNo) {

        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_number", orderNo);
        Order order = orderMapper.selectOne(queryWrapper);
        if(order == null) {
        	return null;
        }
        order.setOrderItems(orderItemService.selectByOrderNo(orderNo));
        order.setOrderAddr(orderAddrService.selectById(order.getOrderAddrId()));
        return order;
    }
    
    /**
     * 查询订单
     * 
     * @param id ID
     * @return 单个对象
     */
    @Override
    @Transactional(readOnly = true)
    public Order selectById(String id) {
    	
    	Order order = orderMapper.selectById(id);
        if(order == null) {
        	return null;
        }
    	order.setOrderItems(orderItemService.selectByOrderNo(order.getOrderNumber()));
        order.setOrderAddr(orderAddrService.selectById(order.getOrderAddrId()));
    	return order;
    }
    
    @Override
	public List<Order> listTimeoutOrder() {
		
    	QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", OrderStatus.UNPAY.value());
        queryWrapper.lt("exp_time", DateUtil.getCurTime());
    	List<Order> list = orderMapper.selectList(queryWrapper);
    	for (Order order : list) {
    		order.setOrderItems(orderItemService.selectByOrderNo(order.getOrderNumber()));
		}
		return list;
	}
    
    @Override
	public List<Order> listUnConfirmPayOrder() {
		
    	QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", OrderStatus.UNPAY.value());
        queryWrapper.ge("exp_time", DateUtil.getDurationMinute(new Date(), -5));//
		return orderMapper.selectList(queryWrapper);
	}
    
    @Override
    public List<Order> listWaitConfirmOrder(int preDayCount) {
    	
    	QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
    	queryWrapper.eq("status", OrderStatus.CONSIGNMENT.value());
    	queryWrapper.lt("dvy_time", DateUtil.getDurationDateStr(-preDayCount, DateUtil.PATTERN_DEFAULT));
    	List<Order> list = orderMapper.selectList(queryWrapper);
    	for (Order order : list) {
    		order.setOrderItems(orderItemService.selectByOrderNo(order.getOrderNumber()));
		}
		return list;
    }

    /**
     * 查询订单列表
     * 
     * @param param
     * @return 
     */
    @Override
    @Transactional(readOnly = true)
    public List<Order> selectList(OrderParam param) {
    
    	QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        
        queryWrapper.eq(Objects.nonNull(param.getShopId()), "shop_id", param.getShopId());
        queryWrapper.eq(StringUtils.isNotBlank(param.getUserId()), "user_id", param.getUserId());
        queryWrapper.eq(StringUtils.isNotBlank(param.getOrderNumber()), "order_number", param.getOrderNumber());
        queryWrapper.eq(Objects.nonNull(param.getPayType()), "pay_type", param.getPayType());
        queryWrapper.eq(Objects.nonNull(param.getStatus()), "status", param.getStatus());
        queryWrapper.eq(StringUtils.isNotBlank(param.getDvyType()), "dvy_type", param.getDvyType());
        queryWrapper.eq(StringUtils.isNotBlank(param.getDvyFlowNo()), "dvy_flow_no", param.getDvyFlowNo());
        queryWrapper.ge(Objects.nonNull(param.getCreateTimeBegin()), "create_time", param.getCreateTimeBegin());
        queryWrapper.le(Objects.nonNull(param.getCreateTimeEnd()), "create_time", param.getCreateTimeEnd());
        
        queryWrapper.eq(Objects.nonNull(param.getIsPayed()), "is_payed", param.getIsPayed());
        queryWrapper.eq(Objects.nonNull(param.getDeleteStatus()), "delete_status", param.getDeleteStatus());
        queryWrapper.eq(Objects.nonNull(param.getRefundSts()), "refund_sts", param.getRefundSts());
        queryWrapper.eq(Objects.nonNull(param.getOrderType()), "order_type", param.getOrderType());
        queryWrapper.eq(Objects.nonNull(param.getCloseType()), "close_type", param.getCloseType());

        return orderMapper.selectList(queryWrapper);
    }

    /**
     * 新增订单
     * 
     * @param order 
     * @return 
     */
    @Override
    @Transactional
    public int insert(Order order) {
    
        return orderMapper.insert(order);
    }

    /**
     * 修改订单
     * 
     * @param order 
     * @return 
     */
    @Override
    @Transactional
    public int update(Order order) {
    
        return orderMapper.updateById(order);
    }
    
    @Override
	public void delivery(DeliveryOrderParam orderParam) {
        Order order = selectSimpleByOrderNo(orderParam.getOrderNumber());
        if (order == null || !StringUtils.equals(TokenUtils.getLoginUserShopId(), order.getShopId())) {
            throw new ParameterErrorException("您没有该数据的权限！");
        }

        Order newOrder = new Order();
        newOrder.setId(order.getId());
        newOrder.setDvyId(orderParam.getDvyId());
        newOrder.setDvyFlowNo(orderParam.getDvyFlowNo());
        newOrder.setDvyTime(new Date());
        newOrder.setStatus(OrderStatus.CONSIGNMENT.value());
        newOrder.setUserId(order.getUserId());
        newOrder.setUpdateTime(new Date());
        orderMapper.updateById(newOrder);
        
        OrderLog orderLog = new OrderLog();
    	orderLog.setCreateBy(TokenUtils.getLoginUsername());
    	orderLog.setCreateTime(new Date());
    	orderLog.setOperType(MallStateConstant.ORDER_OPER_TYPE_SELLER);
    	orderLog.setOperRemark("订单发货！");
    	orderLog.setOrderNumber(order.getOrderNumber());
        orderLogMapper.insert(orderLog);
        
        // 发送用户发货通知
//      Map<String, String> params = new HashMap<>(16);
//      params.put("orderNumber", order.getOrderNumber());
//		Delivery delivery = deliveryMapper.selectById(order.getDvyId());
//		params.put("dvyName", delivery.getDvyName());
//		params.put("dvyFlowId", order.getDvyFlowId());
//		smsLogService.sendSms(SmsType.NOTIFY_DVY, order.getUserId(), order.getMobile(), params);

//        List<OrderItem> orderItems = orderItemService.selectByOrderNo(orderParam.getOrderNo());
//        for (OrderItem orderItem : orderItems) {
//            productService.removeProductCacheById(orderItem.getProdId());
//            skuService.removeSkuCacheBySkuId(orderItem.getSkuId(),orderItem.getProdId());
//        }
		
	}
    
    @Override
	public void addLog(OrderLog orderLog) {
    	Order order = selectSimpleByOrderNo(orderLog.getOrderNumber());
        if (order == null || !StringUtils.equals(TokenUtils.getLoginUserShopId(), order.getShopId())) {
            throw new ParameterErrorException("您没有该数据的权限！");
        }
        
		if(StringUtils.equals(orderLog.getOpType(), "closeOrder")) {
			closeOrder(order, MallStateConstant.ORDER_OPER_TYPE_SELLER);
	        orderLog.setOperRemark(String.format("强制关闭订单, 关闭前状态:%s, 备注：%s", 
	        		OrderStatus.instance(order.getStatus()).getDesc(), orderLog.getOperRemark()));
		}
    	orderLog.setCreateBy(TokenUtils.getLoginUsername());
    	orderLog.setCreateTime(new Date());
    	orderLog.setOperType(MallStateConstant.ORDER_OPER_TYPE_SELLER);
        orderLogMapper.insert(orderLog);
	}
    
    private boolean closeOrder(Order order, Integer operType) {
    	Map<String, Integer> prodCollect = new HashMap<>();
        Map<String, Integer> skuCollect = new HashMap<>();
        if (CollectionUtil.isNotEmpty(order.getOrderItems())) {
        	for (OrderItem orderItem : order.getOrderItems()) {
        		prodCollect.put(orderItem.getProdId(), NumberUtil.add(prodCollect.get(orderItem.getProdId()), orderItem.getProdCount()));
        		skuCollect.put(orderItem.getSkuId(), NumberUtil.add(prodCollect.get(orderItem.getSkuId()), orderItem.getProdCount()));
			}
        }
        
    	if(NumberUtil.eq(operType, MallStateConstant.ORDER_OPER_TYPE_SYS) && orderMapper.isTimeoutOrder(order.getOrderNumber()) == null){
    		logger.error("关闭订单时检查到订单状态已发生改变，已停止关闭订单， orderNo:{}", order.getOrderNumber());
			return false;
    	}
        if(orderMapper.cancelOrder(order) < 1) {
        	logger.error("取消订单时检查到订单状态已发生改变，已停止取消订单， orderNo:{}", order.getOrderNumber());
        	if(NumberUtil.eq(operType, MallStateConstant.ORDER_OPER_TYPE_SYS)) {
    			return false;
    		}
        	throw new BusinessException("订单数据改变，请刷新页面重试！");
        }
        
        if(CollectionUtil.isNotEmpty(prodCollect)) {
        	productMapper.returnStock(prodCollect);
        }
        if(CollectionUtil.isNotEmpty(skuCollect)) {
        	prodSkuMapper.returnStock(skuCollect);
        }
        return true;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelOrder(Order order, Integer operType) {
        
    	if(!closeOrder(order, operType)) {
    		return ;
    	}
        
        OrderLog orderLog = new OrderLog();
    	orderLog.setCreateTime(new Date());
    	orderLog.setOperType(operType);
    	if(NumberUtil.eq(operType, MallStateConstant.ORDER_OPER_TYPE_SYS)) {
    		orderLog.setOperRemark("超时未付款关闭订单！");
    		orderLog.setCreateBy("system");
    	}else {
    		orderLog.setOperRemark("取消订单！");
    		orderLog.setCreateBy(TokenUtils.getLoginUserid());
    	}
		orderLog.setOrderNumber(order.getOrderNumber());
        orderLogMapper.insert(orderLog);
    	
        eventPublisher.publishEvent(new CancelOrderEvent(order));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void confirmOrder(Order order, Integer operType) {
    	
    	Map<String, Integer> prodCollect = new HashMap<>();
        Map<String, Integer> skuCollect = new HashMap<>();
        if (CollectionUtil.isNotEmpty(order.getOrderItems())) {
        	for (OrderItem orderItem : order.getOrderItems()) {
        		prodCollect.put(orderItem.getProdId(), NumberUtil.add(prodCollect.get(orderItem.getProdId()), orderItem.getProdCount()));
        		skuCollect.put(orderItem.getSkuId(), NumberUtil.add(prodCollect.get(orderItem.getSkuId()), orderItem.getProdCount()));
			}
        }
    	
        orderMapper.confirmOrder(order);
        
        if(CollectionUtil.isNotEmpty(prodCollect)) {
        	productMapper.updateSoldNum(prodCollect);
        }
        if(CollectionUtil.isNotEmpty(skuCollect)) {
        	prodSkuMapper.updateSoldNum(skuCollect);
        }
        
        OrderLog orderLog = new OrderLog();
    	orderLog.setCreateTime(new Date());
    	orderLog.setOperType(MallStateConstant.ORDER_OPER_TYPE_BUYER);
    	if(NumberUtil.eq(operType, MallStateConstant.ORDER_OPER_TYPE_SYS)) {
    		orderLog.setOperRemark("订单自动确认收货！");
    		orderLog.setCreateBy("system");
    	}else {
    		orderLog.setOperRemark("订单确认收货！");
    		orderLog.setCreateBy(TokenUtils.getLoginUserid());
    	}
		orderLog.setOrderNumber(order.getOrderNumber());
        orderLogMapper.insert(orderLog);
        
        eventPublisher.publishEvent(new ReceiptOrderEvent(order));
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteOrders(List<Order> orders) {
        orderMapper.deleteOrders(orders);
    }
    
    @Override
    public OrderCountDataVo getOrderCount(String userId) {
        return orderMapper.getOrderCount(userId);
    }
    
    @Override
    @CachePut(cacheNames = "ConfirmOrderCache", key = "#userId")
    public ShopCartOrderMergerVo putConfirmOrderCache(String userId, ShopCartOrderMergerVo shopCartOrderMergerVo) {
        return shopCartOrderMergerVo;
    }
    
    @Override
    @Cacheable(cacheNames = "ConfirmOrderCache", key = "#userId")
    public ShopCartOrderMergerVo getConfirmOrderCache(String userId) {
        return null;
    }
    
    @Override
    @CacheEvict(cacheNames = "ConfirmOrderCache", key = "#userId")
    public void removeConfirmOrderCache(String userId) {
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<Order> submit(String userId, ShopCartOrderMergerVo mergerOrder) {
        // 把订单地址保存到数据库
        OrderAddr orderAddr = BeanUtil.copyProperties(mergerOrder.getUserAddr(), OrderAddr.class);
        if (orderAddr == null) {
            throw new BusinessException("请填写收货地址");
        }
        orderAddr.setUserId(userId);
        orderAddr.setCreateTime(new Date());
        
        List<String> basketIds = new ArrayList<>();
        // 需要更新库存的sku列表
        List<ProdSku> skuStockList = new ArrayList<>();
        // 商品productId为key 需要更新库存的product为value的map
        Map<String, Product> prodStocksMap = new HashMap<>();
        List<OrderSettlement> settlementList = new ArrayList<>();
        List<com.lam.mall.entity.Order> orderList = new ArrayList<>();
        // 每个店铺生成一个订单
        for (ShopCartOrderVo shopCartOrderVo : mergerOrder.getShopCartOrders()) {
        	orderList.add(createOrder(basketIds, skuStockList, prodStocksMap, settlementList, shopCartOrderVo));
        }

        // 删除购物车的商品信息
        if (!basketIds.isEmpty()) {
            basketMapper.deleteShopCartItemsByBasketIds(userId, basketIds);
        }

        // 更新sku库存
        skuStockList.forEach(sku -> {
            if (prodSkuMapper.updateStocks(sku) == 0) {
            	prodSkuService.removeCacheBySkuId(sku.getId(), sku.getProdId());
                throw new BusinessException("商品：[" + sku.getProdName() + "]库存不足");
            }
        });

        // 更新商品库存
        prodStocksMap.forEach((prodId, prod) -> {
            if (productMapper.updateStocks(prod) == 0) {
                productService.removeProductCacheById(prodId);
                throw new BusinessException("商品：[" + prod.getProdName() + "]库存不足");
            }
        });
        
        OrderLog orderLog = new OrderLog();
    	orderLog.setCreateBy(userId);
    	orderLog.setCreateTime(new Date());
    	orderLog.setOperType(MallStateConstant.ORDER_OPER_TYPE_BUYER);
    	orderLog.setOperRemark("用户提交订单！");
    	
        //保存订单
        Date expTime1Day = DateUtil.getDurationMinute(new Date(), 180);
        orderList.forEach(order -> {
        	// 每个订单都有一个订单地址
        	orderAddr.setId(snowflake.nextIdStr());
        	orderAddr.setOrderNumber(order.getOrderNumber());
            orderAddrService.insert(orderAddr);
            
        	order.setOrderAddrId(orderAddr.getId());
        	order.setUserId(userId);
        	order.setExpTime(expTime1Day);
        	orderMapper.insert(order);
        	
        	orderLog.setId(snowflake.nextIdStr());
        	orderLog.setOrderNumber(order.getOrderNumber());
			orderLogMapper.insert(orderLog);
			
        	order.getOrderItems().forEach(orderItem->orderItemService.insert(orderItem));
        });
        //保持结算数据
        settlementList.forEach(t->{
        	t.setUserId(userId);
        	orderSettlementMapper.insert(t);
        });
        
        // 通过发布订单通知
        eventPublisher.publishEvent(new SubmitOrderEvent(mergerOrder, orderList));
        return orderList;
    }

    private Order createOrder(List<String> basketIds, List<ProdSku> skuStockList, 
    		Map<String, Product> prodStocksMap, List<OrderSettlement> settlementList, ShopCartOrderVo shopCartOrderVo) {
        // 使用雪花算法生成的订单号
        String orderNumber = "od" + snowflake.nextIdStr();
        shopCartOrderVo.setOrderNumber(orderNumber);

        String shopId = shopCartOrderVo.getShopId();

        // 订单商品名称
        List<String> orderItemNameList = new ArrayList<>();

        List<OrderItem> orderItems = new ArrayList<>();

        List<ShopCartItemDiscountVo> shopCartItemDiscounts = shopCartOrderVo.getShopCartItemDiscounts();
        for (ShopCartItemDiscountVo shopCartItemDiscount : shopCartItemDiscounts) {
            for (ShopCartItemVo shopCartItem : shopCartItemDiscount.getShopCartItems()) {
                ProdSku sku = checkAndGetSku(shopCartItem, skuStockList);
                Product product = checkAndGetProd(shopCartItem, prodStocksMap);
                OrderItem orderItem = getOrderItem(orderNumber, shopId, shopCartItem, sku, product);
                orderItems.add(orderItem);
                orderItemNameList.add(orderItem.getProdName());
                if (shopCartItem.getId() != null && !StringUtils.equals(shopCartItem.getId(), "0")) {
                    basketIds.add(shopCartItem.getId());
                }
            }
        }

        String orderProdName = StringUtils.list2Str(orderItemNameList);
        // 订单信息
        Order order = getOrder(shopCartOrderVo, orderNumber, shopId, orderProdName, orderItems);
        // 插入订单结算表
        OrderSettlement orderSettlement = new OrderSettlement();
        orderSettlement.setCreateTime(new Date());
        orderSettlement.setOrderNumber(orderNumber);
        orderSettlement.setPayAmount(order.getActualTotal());
        orderSettlement.setPayType(order.getPayType());
        orderSettlement.setPayStatus(PayStatus.UNPAY.value());
        orderSettlement.setVersion(0);
        settlementList.add(orderSettlement);
        return order;
    }

    private Order getOrder(ShopCartOrderVo shopCartOrderVo, String orderNumber, 
    		String shopId, String orderProdName, List<OrderItem> orderItems) {
        Order order = new Order();
        Date now = new Date();
        order.setShopId(shopId);
        order.setOrderNumber(orderNumber);
        order.setProdName(StringUtils.substring(orderProdName, 0, 100));// 订单商品名称
        order.setTotal(shopCartOrderVo.getTotal());// 商品总额
        order.setActualTotal(NumberUtil.subtract(NumberUtil.add(shopCartOrderVo.getTotal(), shopCartOrderVo.getTransfee()), order.getReduceAmount()));// 订单金额
        order.setReduceAmount(shopCartOrderVo.getShopReduce());
        order.setDvyAmount(shopCartOrderVo.getTransfee());
//        order.setPayAmt();
        order.setStatus(OrderStatus.UNPAY.value());
        order.setUpdateTime(now);
        order.setCreateTime(now);
        order.setIsPayed(CommonConstant.NO0);
        order.setDeleteStatus(CommonConstant.DEL_STATUS_NORMAL);
        order.setProductNums(shopCartOrderVo.getTotalCount());
        order.setRemarks(shopCartOrderVo.getRemarks());
        order.setOrderItems(orderItems);
        return order;
    }

    private OrderItem getOrderItem(String orderNumber, String shopId, ShopCartItemVo shopCartItem, 
    		ProdSku sku, Product product) {
        OrderItem orderItem = new OrderItem();
        orderItem.setShopId(shopId);
        orderItem.setOrderNumber(orderNumber);
        orderItem.setProdId(sku.getProdId());
        orderItem.setSkuId(sku.getId());
        orderItem.setSkuName(sku.getSkuName());
        orderItem.setProdCount(shopCartItem.getProdCount());
        orderItem.setProdName(sku.getProdName());
        orderItem.setPic(StringUtils.isBlank(sku.getPic()) ? product.getPic() : sku.getPic());
        orderItem.setPrice(shopCartItem.getPrice());
        orderItem.setTotalAmt(shopCartItem.getProductTotalAmount());
        orderItem.setCreateTime(new Date());
        orderItem.setCommStatus(0);//未评论
        orderItem.setBasketDate(shopCartItem.getBasketDate());
        //推广员卡号
        orderItem.setDistributionNo(shopCartItem.getDistributionCardNo());
        return orderItem;
    }

    private Product checkAndGetProd(ShopCartItemVo shopCartItem, Map<String, Product> prodStocksMap) {
    	String prodId = shopCartItem.getProdId();
        Product product = productService.getSampleProdByIdCache(prodId);
        if (product == null) {
            throw new BusinessException("购物车包含无法识别的商品");
        }
        if (!NumberUtil.eq(product.getStatus(), CommonConstant.STATUS_NORMAL_1)) {
            throw new BusinessException("商品[" + product.getProdName() + "]已下架");
        }

        // 商品需要改变的库存
        Product mapProduct = prodStocksMap.get(prodId);
        if (mapProduct == null) {
            mapProduct = new Product();
            mapProduct.setTotalStocks(0);
            mapProduct.setId(prodId);
            mapProduct.setProdName(product.getProdName());
        }

        if (product.getTotalStocks() != -1) {
            mapProduct.setTotalStocks(mapProduct.getTotalStocks() + shopCartItem.getProdCount());
            prodStocksMap.put(product.getId(), mapProduct);
        }

        // -1为无限库存
        if (product.getTotalStocks() != -1 && mapProduct.getTotalStocks() > product.getTotalStocks()) {
            throw new BusinessException("商品：[" + product.getProdName() + "]库存不足");
        }
        return product;
    }

    private ProdSku checkAndGetSku(ShopCartItemVo shopCartItem, List<ProdSku> skuStockList) {
    	
        // 获取sku信息
        ProdSku sku = prodSkuService.getBySkuIdCache(shopCartItem.getSkuId());
        if (sku == null) {
            throw new BusinessException("购物车包含无法识别的商品");
        }

        if (!NumberUtil.eq(sku.getStatus(), CommonConstant.STATUS_NORMAL_1)) {
            throw new BusinessException("商品[" + sku.getProdName() + "]已下架");
        }
        // -1为无限库存
        if (sku.getStocks() != -1 && shopCartItem.getProdCount() > sku.getStocks()) {
            throw new BusinessException("商品：[" + sku.getProdName() + "]库存不足");
        }

        if (sku.getStocks() != -1) {
        	ProdSku mapSku = new ProdSku();
            mapSku.setProdId(sku.getProdId());
            // 这里的库存是改变的库存
            mapSku.setStocks(shopCartItem.getProdCount());
            mapSku.setId(sku.getId());
            mapSku.setProdName(sku.getProdName());
            skuStockList.add(mapSku);
        }
        return sku;
    }

}
